//发布时间格式化
export function releaseTime(str) {
    if (!str) return '几天前'

    if (typeof str == 'number') {

        let dataJson = getDateJson(str)

        return dataJson.m + '-' + dataJson.d
    }

    return str.match(/-(.+)\s/, '')[1]
}

//获取时间格式
export function getDateJson(time) {
    let now;

    if (typeof time == 'number') {

        now = new Date(time)

    } else {
        now = time ? time : new Date();
    }

    let y = now.getFullYear(),
        m = now.getMonth() + 1,
        d = now.getDate(),
        week = now.getDay();
    return {
        fullDate: y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString()
            .substr(0, 8),
        date: y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d),
        week,
        y,
        m: (m < 10 ? "0" + m : m),
        d: (d < 10 ? "0" + d : d),
        min: now.toTimeString().substr(0, 8)
    }
}

// 日期格式化
export function parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            time = parseInt(time)
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/')
        }
        if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}


/**
 * 深度克隆
 */

 export function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach((keys) => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepClone(source[keys])
        } else {
            targetObj[keys] = source[keys]
        }
    })
    return targetObj
}

//历史记录
export const History = {
    get: function (key) {
        let arr = uni.getStorageSync(key)
        return arr
    },
    set: function (key, value) {

        let arr = uni.getStorageSync(key)

        if (arr) {

            if (arr.indexOf(value) >= 0) {
                arr.splice(arr.indexOf(value), 1)
            }
            if (arr.length >= 10) {
                arr = arr.slice(0, 8)
            }
            arr.unshift(value)
            uni.setStorageSync(key, arr)
        } else {
            uni.setStorageSync(key, [value])
        }
    },
    remove: function (key) {
        uni.removeStorage({
            key: key,
            success: res => {}
        });
    }
}

/**
 * 时间 去除时分秒
 */

 export function onlyDate( str ) {
    
    if(str){
        return str.split(' ')[0]
    }
    return '-'

}

//判断输入为空，没有特殊符号
export const $verifiyStr = (str) => {

    if (!str) {
        uni.showToast({
            title: '关键字不能为空',
            icon: 'none',
            duration: 1000,
        });
        return true;
    }

    if (/[`~!@#$%^&*_\-+=<>?:"\/'\\[\]·~！@#￥%……&*——\-+=？：.]/im.test(str)) {
        uni.showToast({
            title: '关键字不能包含特殊字符',
            icon: 'none',
            duration: 1000,
        });
        return true;
    }

    return false
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
 export function handleTree(data, id, parentId, children, rootId) {
    id = id || 'id'
    parentId = parentId || 'parentId'
    children = children || 'children'
    rootId =
        rootId ||
        Math.min.apply(
            Math,
            data.map((item) => {
                return item[parentId]
            })
        ) ||
        '0'
       let nums = 1 
    //对源数据深度克隆
    const cloneData = JSON.parse(JSON.stringify(data))
    //循环所有项
    const treeData = cloneData.filter((father) => {
        let branchArr = cloneData.filter((child) => {
            //返回每一项的子级数组
            child.key =  nums++

            return father[id] === child[parentId]
        })
        branchArr.length > 0 ? (father.children = branchArr) : ''
        //返回第一层
        return (
            father[parentId] === rootId || father[parentId] === Number(rootId)
        )
    })
    return treeData != '' ? treeData : data
}


export function CountTime (endTime) {

    endTime = endTime || "2023/9/21 21:00:00";

    // console.log('123123123123123',endTime)

    //获取当前时间  
    var date = new Date();
    var now = date.getTime();
    //设置截止时间  

    var endDate = new Date(endTime);
    var end = endDate.getTime();

    //时间差  
    var leftTime = end - now;
    //定义变量 d,h,m,s保存倒计时的时间  

    var d, h, m, s;
    if (leftTime >= 0) {
        d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
        h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
        m = Math.floor(leftTime / 1000 / 60 % 60);
        s = Math.floor(leftTime / 1000 % 60);
    }
    else{
        return false
    }

    h = h < 10 ? '0' + h : h
    m = m < 10 ? '0' + m : m
    s = s < 10 ? '0' + s : s

    return { d, h, m, s }
    //将倒计时赋值到div中  
}